<?php

namespace app\index\controller;

use app\common\controller\HomeBase;
use think\Db;

class Article extends HomeBase {
    
    public function index() {
        $id = input('param.id');
        
        if($id){
            $data = Db::name('Article')->find($id);
            if(!$data){
                abort(404, '电影资讯不存在'); 
            }else{
                //高效率随机获取同类型电影
                $data2 = Db::query('SELECT m2.id,title FROM zhuzong_article AS m   
JOIN   
(SELECT   
    ROUND(  
        RAND() * ((SELECT MAX(id) FROM zhuzong_article)-(SELECT MIN(id) FROM zhuzong_article))   
        + (SELECT MIN(id) FROM zhuzong_article)  
    ) AS id  
) AS m2   
WHERE m.id>=m2.id limit 11');
            }  
        }else{
            abort(404, '电影资讯不存在');
        }
        
        $data3 = $this->moreMovies($id);
        
        //增加浏览量
        Db::name('Article')->where(['id'=>$id])->setInc('reading');
        
        //去掉所有的img标签
        return $this->fetch('',['data'=>preg_replace('/<img[^>]+>/i','',$data),'data2'=>$data2,'data3'=>$data3,'title'=>$data['title']]);
    }
    
    
    //推荐该类其他电影
    public function moreMovies ($id,$page=0) {
        $num = $page*12;
        $limit = "$num,12";
        $data = Db::name('Article')->cache(3600)->field('id,title')->where(['id'=>['neq',$id]])->order('publish_time desc')->limit($limit)->select();
        
        if($this->request->isAjax()){
            $this->view->engine->layout(false); 
            return $this->fetch('recommended',['data'=>$data]);
        }else{
            return $data;
        }
    }
}
